﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Kooboo.Domain;
using Kooboo.IoC;

namespace Kooboo.Commerce.Contexts.Brands
{
    public static class EditorBehavior
    {
        public static void Post(this IEditor actor, IBrand brand)
        {
            var repository = ContextContainer.Current.Resolve<IBrandRepository>();
            var find = repository.Brands
               .Any(i => i.Name == brand.Name);


            if (find)
            {
                throw new System.Data.DuplicateNameException(brand.Name);
            }

            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    repository.Post(brand);
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public static void Put(this IEditor actor, IBrand brand)
        {
            var repository = ContextContainer.Current.Resolve<IBrandRepository>();
            var find = repository.Brands
                .Where(i => i.Name == brand.Name)
                .Select(i => i.Id)
                .FirstOrDefault();

            if (find != 0 && find != brand.Id)
            {
                throw new System.Data.DuplicateNameException(brand.Name);
            }

            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    repository.Put(brand);
                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }

        public static void Delete(this IEditor actor, IBrand brand)
        {

            using (var transaction = ObjectContainer.CreateInstance<TransactionContext>())
            {
                try
                {
                    var repository = ContextContainer.Current.Resolve<IBrandRepository>();

                    brand.Products
                      .ToUpdate()
                      .Set(i => i.Brand, null)
                      .Execute();


                    repository.Delete(brand);

                    transaction.Commit();
                }
                catch
                {
                    transaction.Rollback();
                    throw;
                }
            }
        }
    }
}
